<?php
/**
 * 数字证书管理
 * Enter description here ...
 * @author cc
 *
 */
namespace Home\Controller;
use Think\Controller;
class CertificatesController extends CommonController{
	public function index(){
		$this->display();
	}
	
	public function nav(){
		$dept = M("sys_dept");
		$data1 = $dept->where('dept_level=0')->order('dept_no asc')->select();//查询一级部门
		if(!empty($data1)){
			foreach ($data1 as $key1=>$value1){
				$dept_id1 = $value1['id'];
				$data2 = $dept->where('dept_level='.$dept_id1)->order('dept_no asc')->select();//查询二级部门
				if(!empty($data2)){
					foreach ($data2 as $key2=>$value2){
						$dept_id2 = $value2['id'];
						$data3 = $dept->where('dept_level='.$dept_id2)->order('dept_no asc')->select();//查询三级部门
						if(!empty($data3)){
							foreach ($data3 as $key3=>$value3){
								$dept_id3 = $value3['id'];
								$data4 = $dept->where('dept_level='.$dept_id3)->order('dept_no asc')->select();//查询四级部门
								if(!empty($data4)){
									foreach ($data4 as $key4=>$value4){
										$dept_id4 = $value4['id'];
										$data5 = $dept->where('dept_level='.$dept_id4)->order('dept_no asc')->select();//查询五级部门
										if(!empty($data5)){
											foreach ($data5 as $key5=>$value5){//如果级别很多的话，就继续写
//												$dept_id5 = $value5['id'];
//												$data6 = $dept->where('dept_level='.$dept_id5)->order('dept_no asc')->select();//查询六级部门
//												if(!empty($data6)){
//													
//												}
												$data[$key1]['one'][$key2]['two'][$key3]['three'][$key4]['four'][$key5]['dept_id'] = $value5['id'];
												$data[$key1]['one'][$key2]['two'][$key3]['three'][$key4]['four'][$key5]['dept_name'] = $value5['dept_name'];
											}
										}
										$data[$key1]['one'][$key2]['two'][$key3]['three'][$key4]['dept_id'] = $value4['id'];
										$data[$key1]['one'][$key2]['two'][$key3]['three'][$key4]['dept_name'] = $value4['dept_name'];
									}
								}
								$data[$key1]['one'][$key2]['two'][$key3]['dept_id'] = $value3['id'];
								$data[$key1]['one'][$key2]['two'][$key3]['dept_name'] = $value3['dept_name'];
							}
						}
						$data[$key1]['one'][$key2]['dept_id'] = $value2['id'];
						$data[$key1]['one'][$key2]['dept_name'] = $value2['dept_name'];
					}
				}
				$data[$key1]['dept_id'] = $value1['id'];
				$data[$key1]['dept_name'] = $value1['dept_name'];
			}
			
		}
		
		$this->assign('data',$data);
		$this->display();
	}
	
	public function lists(){
		$user = M("sys_user");
		$dept_id = I('get.dept_id', 1,'intval');
		
		$cakey = M("sys_user_cakey");
		$model = M();
		$count = $user->where('dept_id='.$dept_id)->count();
		$page = new \Think\Page($count,C("PAGE_LIST_ROWS"));
		$show = $page->show();
		$sql = "select user.*, dept.dept_name from oa_sys_user user,oa_sys_dept dept where user.dept_id = dept.id and user.dept_id=$dept_id limit ".$page->firstRow.",".$page->listRows;
		$data = $model->query($sql);
		foreach($data as $key=>$value){
			$user_name = $value['user_name'];
			$data[$key]['key'] = $cakey->where("user_name = '$user_name'")->getField('key');
		}
		$this->assign('data',$data);
		$this->assign("dept_id",$dept_id);
		$this->assign("empty",emptyhtml("list"));
		$this->assign("page",$show);
		$this->display();
	}
	
	public function issued(){//生成证书
		$id = I('get.id');
		$dept_id = I('get.dept_id');
		if( !is_id($id) || !is_id($dept_id) ){ $this->error("非法参数！"); }
		$cakey = M("sys_user_cakey");
		$user = M("sys_user");
		$user_name = $user->where("id=%d", $id)->getField("user_name");
		$name = $user->where("id=%d", $id)->getField("name");
		$email = $user->where("id=%d", $id)->getField("email");
		if( empty($user_name) ){
			$this->error("未查到对应的用户！");
		}elseif( empty($email) ){
			$this->error("未查到该用户的邮箱！");
		}else{//证书

			//ca客户端私钥
			$code = $this->key();
			//windows 下生成证书的方式；
			
			$pri_path = "d:/Wamp/private/".$user_name;
			$cer_path = "d:/Wamp/certificates/".$user_name;
			$cacrt_path = "D:/Wamp/Apache24/conf/ca.crt";
			$cakey_path = "D:/Wamp/Apache24/bin/ca.key";
			if(is_file( $pri_path.".key.pem" )){
				unlink( $pri_path.".key.pem" );
				unlink( $cer_path.".crt" );
				unlink( $pri_path.".csr" );
				unlink( $cer_path.".p12" );
			}
			$openssl_path = "d:/Wamp/Apache24/bin/";
			$cmd1 = "openssl genrsa -aes256 -passout pass:$code -out ".$pri_path.".key.pem 2048";
			$cmd2 = "openssl req -passin pass:$code -new -key ".$pri_path.".key.pem -out ".$pri_path.".csr -subj \"/C=CN/ST=SZ/L=SZ/O=cc1990/OU=cc1990/CN=192.168.1.203\" -config D:/Wamp/Apache24/conf/openssl.cnf";
			$cmd3 = "openssl x509 -req -days 3650 -CA ".$cacrt_path." -CAkey ".$cakey_path." -CAcreateserial -in ".$pri_path.".csr -out ".$cer_path.".crt";
			$cmd4 = "openssl pkcs12 -export -clcerts -inkey ".$pri_path.".key.pem -in ".$cer_path.".crt -out ".$cer_path.".p12 -passin pass:$code -passout pass:$code";
			
			
			exec( $openssl_path.$cmd1 );
			exec( $openssl_path.$cmd2 );
			exec( $openssl_path.$cmd3 );
			exec( $openssl_path.$cmd4 );
			
			//linux下生成证书的方式；
			//system("/usr/local/apache/htdocs/oa/Scripts/ca.sh $user_name $code", $status);
			if( is_file("/usr/local/certificates/".$user_name.".p12") ){
				//将生成的根证书和密码通过邮件发送给用户
				$success = $this->sendEmail($email, $code, $user_name, $name);
				if($success == '1'){
					$this->success("数字登陆证书发送成功");
				}else{
					$this->error( $success );
				}
			}else{
				$this->error( "未能生成有效的根证书！" );
			}
		}
	}
	
	public function logoff(){//吊销证书
		$id = I('get.id');
		$dept_id = I('get.dept_id');
		if( !is_id($id) || !is_id($dept_id) ){ $this->error("非法参数！"); }
		$cakey = M("sys_user_cakey");
		$user = M("sys_user");
		$user_name = $user->where("id=%d", $id)->getField("user_name");
		
		$id = I('get.id');
		$dept_id = I('get.dept_id');
		if( !is_id($id) || !is_id($dept_id) ){ $this->error("非法参数！"); }
		$cakey = M("sys_user_cakey");
		$user = M("sys_user");
		$user_name = $user->where("id=%d", $id)->getField("user_name");
		
		
	}
	
	public function key(){//生成ca根认证密码
		$str = "01234567890qwertyuiopasdfghjlkzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
		for($i=0; $i<strlen($str);$i++){
			$str_arr[] = substr($str, $i, 1);
		}
		$code = "";
		for($i=0;$i<10;$i++){
			$code .= $str[rand(0, (count($str_arr)-1))];
		}
		return $code;
	}
	
	public function sendEmail($to_email, $key, $user_name, $to_username){
		$time = date('Y-m-d H:i:s');
		Vendor('phpmailer.PHPMailer');
		$cer_path = "/usr/local/certificates/".$user_name;
		
		
		$mail = new \PHPMailer();
		
		$mail->IsSMTP();//使用smtp方式发送
		$mail->Host = '192.168.0.1';
		$mail->SMTPAuth = true;//smtp验证功能；
		$mail->Username = 'oa@cc1990.com';//smtp用户名
		$mail->Password = 'cc1990.com';//smtp密码
		$mail->From = 'oa@cc1990.com';//发件人
		$mail->FromName = "OA系统管理员";//发件人姓名
		$mail->AddAddress("$to_email", "$to_username");
		$mail->AddAttachment($cer_path.".p12", $user_name.".p12"); // 添加附件,并指定名称
		$mail->AddAttachment($cer_path.".crt",$user_name.".crt"); // 添加附件,并指定名称
		
		$mail->IsHTML(true);
		$mail->CharSet = "utf-8";
		$mail->Subject = "OA系统用户登陆证书下载";
		$content = "<body>";
		$content .= "OA系统用户  <font color='red' >$to_username</font> 你好：<br><br>OA系统管理员发送给您一封用户登录证书邮件";
		$content .= "<b>一、证书附件密码：<font color='red' >$key</font></b><br><br>";
		$content .= "<b>二、证书安装步骤如下（chrome浏览器测试）：</b><br>";
		$content .= "<font color='red' ><b>注意：如果你使用的是火狐浏览器访问，本证书的安装方法请看最下面《火狐浏览器下证书的导入》的介绍 </b></font><br><br>";
		$content .= "1、在浏览器中输入OA地址，https://oa.cc1990.com:9000，如果提示如下或者提示无法访问，则需要导入证书<br>";
		$content .= "<img src='http://bbs.cc1990.com/data/attachment/album/201410/13/160349c0izy8gsgr99sisr.jpg' /><br><br>";
		$content .= "2、从邮件附件中下载证书附件：<font color='red' >$user_name.p12</font> 然后双击运行安装<br>";
		$content .= "<img src='http://bbs.cc1990.com/data/attachment/album/201410/13/160349iy9xajusrxc2oaoc.jpg' /><br><br>";
		$content .= "3、下一步、默认<br>";
		$content .= "<img src='http://bbs.cc1990.com/data/attachment/album/201410/13/160350xjci7lceujj76ldu.jpg' /><br><br>";
		$content .= "4、输入邮件中的证书密码<br>";
		$content .= "<img src='http://bbs.cc1990.com/data/attachment/album/201410/13/160350mm3n2w8btm2mwb35.jpg' /><br><br>";
		$content .= "5、如果输入的密码错误，则会提示：输入的密码不正确<br>";
		$content .= "<img src='http://bbs.cc1990.com/data/attachment/album/201410/13/160350nv5pp8rqnovpn65z.jpg' /><br><br>";
		$content .= "6、下一步<br>";
		$content .= "<img src='http://bbs.cc1990.com/data/attachment/album/201410/13/160350ilhghswhfxseiixy.jpg' /><br><br>";
		$content .= "7、下一步<br>";
		$content .= "<img src='http://bbs.cc1990.com/data/attachment/album/201410/13/160351iwit4pt37jjutlit.jpg' /><br><br>";
		$content .= "8、证书导入成功<br>";
		$content .= "<img src='http://bbs.cc1990.com/data/attachment/album/201410/13/160351bqagdgaaqqk5f4ju.jpg' /><br><br>";
		$content .= "---------------------------------------火狐浏览器下证书的导入--------------------------------------";
		$content .= "1、从邮件附件中下载证书附件：<font color='red' >$user_name.crt</font><br>";
		$content .= "2、打开火狐浏览器--> 工具 --> 选项 --> 高级 --> 证书 --> 查看证书<br>";
		$content .= "3、选择您的证书选项卡，然后点击导入<br><img src='http://bbs.cc1990.com/data/attachment/album/201410/22/104202qrqdayqdscdqsrqn.jpg' /><br><br>";
		$content .= "4、选择刚才下载的<font color='red' >$user_name.crt</font>证书<br><img src='http://bbs.cc1990.com/data/attachment/album/201410/22/104202tm7j1n6moejoo2o7.jpg' /><br><br>";
		$content .= "5、输入邮件中的证书密码<br>";
		$content .= "<img src='http://bbs.cc1990.com/data/attachment/album/201410/22/104202m88vxz3mm0l03yvc.jpg' /><br><br>";
		$content .= "6、点击确定，如果输入的密码正确的话，则会提示导入成功，否则请重新输入密码<br>";
		$content .= "<img src='http://bbs.cc1990.com/data/attachment/album/201410/22/105045trmmhkfmxt8z8ch4.jpg' /><br><br>";
		$content .= "</body>";
		$mail->Body = $content;
		$mail->AltBody = "这是一封修改OA系统用户名密码的邮件";
		
		if(!$mail->Send()){
			return "客户端证书邮件发送失败，错误原因：".$mail->ErrorInfo;
			//$this->error("客户端证书邮件发送失败，错误原因：".$mail->ErrorInfo);
		}else{
			M("sys_user_cakey")->where("user_name='%s'", $user_name)->delete();
			$data = array(
				'user_name' => $user_name,
				'name' => $to_username,
				'key' => $key,
				'ca' => $user_name.".p12",
				'time' => date('Y-m-d H:i:s'),
				'author' => session("user_name")
			);
			M("sys_user_cakey")->data($data)->add();
			return '1';
		}
	}
}
?>